﻿using DAL.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL.Dao
{
    public class MessageDaoimpl: Base, IMessageDao
    {
        public int ExistNum { get { return DbEntity.expressDBEntities.Message.Count(); } private set { } }


        public Message GetMessageInfo(int id)
        {
            return  (from i in DbEntity.expressDBEntities.Message where i.ID==id select i).ToList().FirstOrDefault();
        }
        public IList<Message> GetMessageInfoList(int userID)
        {
            return (from i in DbEntity.expressDBEntities.Message where i.UserID == userID select i ).ToList();
        }
        public (int,IList<Message>) GetList(int rows,int page)
        {
            DbEntity.CheckConn();
            var rs = (from i in DbEntity.expressDBEntities.Message select i).ToList();
            return (GetTotalPages(rs.Count, rows),rs.Skip((page-1)*rows).Take(rows).ToList());
        }
        public IList<Message> GetList()
        {
            DbEntity.CheckConn();
            return (from i in DbEntity.expressDBEntities.Message select i).ToList();
        }

        public (int, IList<Message>) GetMessageInfoList(int userID, int rows, int page)
        {
            DbEntity.CheckConn();
            var rs = (from i in DbEntity.expressDBEntities.Message where i.UserID==userID select i).ToList();
            return (GetTotalPages(rs.Count, rows), rs.Skip((page - 1) * rows).Take(rows).ToList());
        }



        public int Add(Message message)
        {
            DbEntity.CheckConn();
            var seq = GetList();
            if (seq.Count == 0) message.ID = 0;
            else
            {
                message.ID =seq.Last().ID + 1;
            }
            DbEntity.expressDBEntities.Message.Add(message);
            DbEntity.expressDBEntities.SaveChanges();
            return message.ID;
        }
        public bool Delete(int id)
        {
            DbEntity.CheckConn();
            Message message = GetMessageInfo(id);
            if (message == null) return false;
            DbEntity.expressDBEntities.Message.Remove(message);
            DbEntity.expressDBEntities.SaveChanges();
            return true;
        }
        public void Dispose()
        {

        }
    }
}
